package com.ysd.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {
	private final static String DRIVER = "com.mysql.jdbc.Driver";
	private final static String URL = "jdbc:mysql://localhost:3306/jiajuxiangmu";
	private final static String USER = "root";
	private final static String PWD = "admin";
	
	//��ȡ����
	public static Connection getConnection() {
		try {
			//1.��������
			Class.forName(DRIVER);
			//2.��������
			Connection conn = DriverManager.getConnection(URL, USER, PWD);
			return conn;//���������������, �򷵻�����
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;//����쳣, �򷵻�null
	}
	
	//ִ��sql���, �������ݿ���Ӱ�������
	public static int executeUpdate(String sql) {//"insert into grade values(null,'09��')"
		Connection conn = getConnection();
		Statement st = null;
		try {
			//3.����Statement����
			st = conn.createStatement();
			//4.ִ��sql���
			int n = st.executeUpdate(sql);//"insert into grade values(null,'09��')"
			return n;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		} finally {//����ִ��try����catch, finally����ִ��
			closeAll(conn, st, null);
		}
	}
	
	//ר�������ر�����
	public static void closeAll(Connection conn, Statement st, ResultSet rs) {
		try {
			//6.�ر���
			if(rs!=null) {
				rs.close();
			}
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();//��ӡ������Ϣ
		}
	}
	
}
